package com.ruoyi.web.controller.blog;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.system.domain.BlogUser;
import com.ruoyi.system.service.IBlogUserService;

/**
 * 博客用户Controller
 * 
 * @author ruoyi
 * @date 2024-01-01
 */
@RestController
@RequestMapping("/blog/user")
public class BlogUserController extends BaseController
{
    @Autowired
    private IBlogUserService blogUserService;

    /**
     * 用户注册
     */
    @Anonymous
    @PostMapping("/register")
    public AjaxResult register(@RequestBody BlogUser blogUser)
    {
        // 参数校验
        if (StringUtils.isEmpty(blogUser.getUsername()))
        {
            return error("用户名不能为空");
        }
        if (StringUtils.isEmpty(blogUser.getPassword()))
        {
            return error("密码不能为空");
        }
        if (StringUtils.isEmpty(blogUser.getEmail()))
        {
            return error("邮箱不能为空");
        }

        // 校验用户名唯一性
        if (!blogUserService.checkUsernameUnique(blogUser.getUsername()))
        {
            return error("用户名已存在");
        }

        // 校验邮箱唯一性
        if (!blogUserService.checkEmailUnique(blogUser.getEmail()))
        {
            return error("邮箱已被注册");
        }

        // 注册用户
        int result = blogUserService.registerUser(blogUser);
        if (result > 0)
        {
            return success("注册成功");
        }
        else
        {
            return error("注册失败");
        }
    }

    /**
     * 用户登录
     */
    @Anonymous
    @PostMapping("/login")
    public AjaxResult login(@RequestBody Map<String, String> loginForm, HttpServletRequest request)
    {
        String username = loginForm.get("username");
        String password = loginForm.get("password");

        // 参数校验
        if (StringUtils.isEmpty(username))
        {
            return error("用户名不能为空");
        }
        if (StringUtils.isEmpty(password))
        {
            return error("密码不能为空");
        }

        // 用户登录
        BlogUser user = blogUserService.login(username, password);
        if (user != null)
        {
            // 更新登录信息
            user.setLoginIp(IpUtils.getIpAddr(request));
            user.setLoginDate(new Date());
            blogUserService.updateUserLoginInfo(user);

            // 返回用户信息（不包含密码）
            Map<String, Object> result = new HashMap<>();
            result.put("user", user);
            result.put("token", "blog_user_" + user.getUserId()); // 简单的token生成，实际项目中应使用JWT
            
            return AjaxResult.success("登录成功", result);
        }
        else
        {
            return error("用户名或密码错误");
        }
    }

    /**
     * 获取用户信息
     */
    @GetMapping("/profile")
    public AjaxResult profile(@RequestParam Long userId)
    {
        BlogUser user = blogUserService.selectBlogUserByUserId(userId);
        if (user != null)
        {
            // 清空敏感信息
            user.setPassword(null);
            return success(user);
        }
        else
        {
            return error("用户不存在");
        }
    }

    /**
     * 更新用户信息
     */
    @PutMapping("/profile")
    public AjaxResult updateProfile(@RequestBody BlogUser blogUser)
    {
        // 不允许修改用户名、邮箱等关键信息
        BlogUser existUser = blogUserService.selectBlogUserByUserId(blogUser.getUserId());
        if (existUser == null)
        {
            return error("用户不存在");
        }

        // 只允许修改部分字段
        existUser.setNickname(blogUser.getNickname());
        existUser.setBio(blogUser.getBio());
        existUser.setGender(blogUser.getGender());
        existUser.setBirthday(blogUser.getBirthday());
        existUser.setPhone(blogUser.getPhone());
        existUser.setAvatar(blogUser.getAvatar());

        int result = blogUserService.updateBlogUser(existUser);
        if (result > 0)
        {
            return success("更新成功");
        }
        else
        {
            return error("更新失败");
        }
    }

    /**
     * 修改密码
     */
    @PutMapping("/password")
    public AjaxResult updatePassword(@RequestBody Map<String, String> passwordForm)
    {
        Long userId = Long.valueOf(passwordForm.get("userId"));
        String oldPassword = passwordForm.get("oldPassword");
        String newPassword = passwordForm.get("newPassword");

        // 参数校验
        if (StringUtils.isEmpty(oldPassword))
        {
            return error("原密码不能为空");
        }
        if (StringUtils.isEmpty(newPassword))
        {
            return error("新密码不能为空");
        }

        int result = blogUserService.updateUserPassword(userId, oldPassword, newPassword);
        if (result > 0)
        {
            return success("密码修改成功");
        }
        else
        {
            return error("原密码错误");
        }
    }

    /**
     * 重置密码
     */
    @Anonymous
    @PostMapping("/reset-password")
    public AjaxResult resetPassword(@RequestBody Map<String, String> resetForm)
    {
        String email = resetForm.get("email");
        String newPassword = resetForm.get("newPassword");
        String verifyCode = resetForm.get("verifyCode");

        // 参数校验
        if (StringUtils.isEmpty(email))
        {
            return error("邮箱不能为空");
        }
        if (StringUtils.isEmpty(newPassword))
        {
            return error("新密码不能为空");
        }
        if (StringUtils.isEmpty(verifyCode))
        {
            return error("验证码不能为空");
        }

        // TODO: 验证邮箱验证码
        // 这里简化处理，实际项目中需要验证邮箱验证码

        int result = blogUserService.resetPassword(email, newPassword);
        if (result > 0)
        {
            return success("密码重置成功");
        }
        else
        {
            return error("邮箱不存在");
        }
    }

    /**
     * 检查用户名是否可用
     */
    @Anonymous
    @GetMapping("/check-username")
    public AjaxResult checkUsername(@RequestParam String username)
    {
        boolean isUnique = blogUserService.checkUsernameUnique(username);
        return success(isUnique);
    }

    /**
     * 检查邮箱是否可用
     */
    @Anonymous
    @GetMapping("/check-email")
    public AjaxResult checkEmail(@RequestParam String email)
    {
        boolean isUnique = blogUserService.checkEmailUnique(email);
        return success(isUnique);
    }
}